import GamePage from './gamePage.js';

class Main {
  constructor() {
    console.log('主程序初始化');
    
    try {
      this.canvas = wx.createCanvas();
      this.context = this.canvas.getContext('2d');
      this.currentPage = null;
      
      this.init();
    } catch (error) {
      console.error('主程序初始化失败:', error);
    }
  }
  
  init() {
    console.log('设置Canvas尺寸');
    
    // 设置Canvas尺寸 - 使用整数尺寸
    const systemInfo = wx.getSystemInfoSync();
    
    // 使用整数尺寸，避免小数导致的模糊
    this.canvas.width = Math.round(systemInfo.windowWidth);
    this.canvas.height = Math.round(systemInfo.windowHeight);
    
    console.log('Canvas尺寸:', this.canvas.width, this.canvas.height);
    console.log('屏幕尺寸:', systemInfo.screenWidth, 'x', systemInfo.screenHeight);
    
    // 创建游戏页面
    try {
      this.currentPage = new GamePage(this.canvas, this.context);
      this.currentPage.init();
      console.log('游戏页面初始化成功');
    } catch (error) {
      console.error('游戏页面初始化失败:', error);
      
      wx.showModal({
        title: '初始化失败',
        content: '游戏初始化失败，请重启',
        showCancel: false
      });
    }
    
    // 绑定全局事件
    this.bindGlobalEvents();
  }
  
  bindGlobalEvents() {
    // 监听屏幕旋转
    wx.onWindowResize((res) => {
      console.log('屏幕尺寸变化:', res);
      const { windowWidth, windowHeight } = res;
      
      // 更新Canvas尺寸 - 使用整数尺寸
      this.canvas.width = Math.round(windowWidth);
      this.canvas.height = Math.round(windowHeight);
      
      // 重新初始化页面
      if (this.currentPage) {
        this.currentPage.destroy();
        this.currentPage = new GamePage(this.canvas, this.context);
        this.currentPage.init();
        
        // 如果之前是在游戏中，重新开始游戏
        if (this.currentPage.isActive) {
          this.currentPage.startGame();
        }
      }
    });
    
    // 小游戏生命周期
    wx.onShow(() => {
      console.log('小游戏显示');
    });
    
    wx.onHide(() => {
      console.log('小游戏隐藏');
    });
  }
}

// 启动游戏
try {
  new Main();
  console.log('游戏启动成功');
} catch (error) {
  console.error('游戏启动失败:', error);
  
  wx.showModal({
    title: '启动失败',
    content: '游戏启动失败，请检查资源文件',
    showCancel: false
  });
}